<template>
  <!-- 商品添加修改页面 -->
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? '新增图片' : '编辑图片'"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="productId" label="商品名称">
        <ComSelectPage ref="newPageSelect" @selectPageChange="e=>dataForm.productId=e"
                       :getUrl="{
        url:'/api/product/page',
        method:'get',
        params:{page: 1,limit: 10,total: 0},
      }" clearable :defaultValue="dataForm.productId" selectLabel="productName" selectValue="id" selectLabelTwo="groupName"></ComSelectPage>
      </el-form-item>
      <el-form-item prop="imgType" label="图片类型">
        <ren-radio-group v-model="dataForm.imgType" dict-type="img_type"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="radio" label="多图上传">
        <el-radio-group v-model="radio" size="small">
          <el-radio :label="false" :disabled="redioDisabled">否</el-radio>
          <el-radio :label="true" :disabled="redioDisabled">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="sort" label="图片排序">
        <el-input-number v-model="dataForm.sort" :precision="0" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="imgUrl" label="" v-if="!radio">
        <div class="flex_center flex_wrap">
          <div class="img_con" v-if="dataForm.imgUrl">
            <el-image class="deduct_img" :src="dataForm.imgUrl" :preview-src-list="[dataForm.imgUrl]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(dataForm.imgUrl)"/>
          </div>
          <com-upload v-show="!dataForm.imgUrl" @get-url="getUrlOne"></com-upload>
        </div>
      </el-form-item>
      <el-form-item prop="imgUrlList" label="" v-if="radio">
        <div class="flex_center flex_wrap">
          <div v-for="(i, index) in dataForm.imgUrlList" :key="index" class="img_con">
            <el-image class="deduct_img" :src="i" :preview-src-list="[i]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(i,index)"/>
          </div>
          <com-upload v-show="dataForm.imgUrlList.length<limit" @get-url="getUrl"></com-upload>
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import {getDictDataList} from '@/utils'

export default {
  data() {
    return {
      visible: false,
      dialogVisible: false,
      radio:false,//是否多图上传
      redioDisabled:false,
      limit: 9,//图片长度
      options: [],
      dataForm: {
        id: '',
        imgUrl: '', //商品的图片路径或链接
        imgUrlList:[],//多图数据
        imgType: '0', //	图片类别字段,用于区分不同类型的图片（如详情页0轮播图、1细节图等）
        productId: '', //关联到所属商品的ID
        sort: '', //用来显示商品在列表中的顺序
      }
    }
  },
  computed: {
    dataRule() {
      return {
        productId: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        imgType: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.redioDisabled = false
        this.dataForm.imgUrlList = []
        this.dataForm.imgUrl = ''
        if (this.dataForm.id) {
          this.redioDisabled = true
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/api/productAlbum/${this.dataForm.id}`).then(({data: res}) => {
        //console.log(res)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        /*处理数组返回null字符*/
        const {id,imgUrl,imgType,productId,sort} = res.data
        const item = {id,imgUrl,imgType,productId,sort}
        this.dataForm = {
          ...this.dataForm,
          ...item
        }
        //console.log(this.dataForm)
      }).catch(() => {
      })
    },
    // 添加单图添加
    getUrlOne(getUrl){
      this.dataForm.imgUrl = getUrl
    },
    // 添加多图添加
    getUrl(getUrl) {
      this.dataForm.imgUrlList.push(getUrl)
    },
    // 删除服务器图片
    cancelImg(url, index) {
      console.log(url)
      console.log(index)
      this.$http({
        url: `/sys/oss/deleteByUrl`,
        method: 'delete',
        data: {url: url},
      }).then(({data: res}) => {
        //console.log('res')
        //console.log(res)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (index ||index === 0){
          this.dataForm.imgUrlList.splice(index, 1)
          return
        }
        if (!index){
          this.dataForm.imgUrl = ''
        }
        if (this.dataForm.id){
          this.$http['put']('/api/productAlbum', this.dataForm).then(({data: res}) => {
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        }
      }).catch((err) => {
        //console.log('err')
        //console.log(err)
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.radio){
          delete this.dataForm.imgUrl
        }
        if (!this.radio){
          delete this.dataForm.imgUrlList
        }
        delete this.dataForm.radio
        this.$http[!this.dataForm.id ? 'post' : 'put']('/api/productAlbum', this.dataForm).then(({data: res}) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, {'leading': true, 'trailing': false}),
  }
}
</script>
<style>
.el-upload el-upload-picture-card {
  display: none;
}

.img_con {
  position: relative;
  display: flex;
}

.deduct_img {
  width: 140px;
  height: 140px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.remove_img {
  position: absolute;
  right: 5px;
  top: -5px;
  color: red;
  cursor: pointer;
}
</style>
